#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h> 
#include "ui.h"
#include "lvgl/src/misc/lv_timer.h" // 确保包含必要的头文件

// 全局变量
extern lv_obj_t *ui_TextArea3;  // 用户名输入框
extern lv_obj_t *ui_TextArea4;  // 密码输入框
extern lv_obj_t *ui_TextArea5;  // Screen4的文本框1
extern lv_obj_t *ui_TextArea6;  // Screen4的文本框2
extern lv_obj_t *ui_TextArea7;  // Screen4的文本框3
extern lv_obj_t *ui_TextArea8;  // Screen4的文本框4
extern lv_obj_t *ui_TextArea22;  // 文本框对象
extern lv_obj_t *ui_Label15;     // 标签对象
extern lv_obj_t *ui_Screen6;   
extern lv_obj_t *ui_Screen7;  
extern lv_obj_t *ui_Button3;    // 登录按钮
extern lv_obj_t *ui_Button4;    // Screen4的确认按钮
extern lv_obj_t *ui_Screen3;    // 目标屏幕
extern lv_obj_t *ui_Screen4;    // Screen4

extern lv_obj_t *ui_Calendar1;    // 日历控件
extern lv_obj_t *ui_TextArea13;   // 显示天数的文本框
extern lv_obj_t *ui_TextArea14;   // 显示小时的文本框

// 本地全局变量
static lv_obj_t *kb = NULL;     // 键盘对象
static lv_obj_t *error_label = NULL;
static lv_obj_t *current_kb_parent = NULL; // 当前键盘的父对象
static lv_timer_t *time_update_timer = NULL;

//全局变量来记录是从哪个屏幕跳转过来的
static lv_obj_t * previous_screen = NULL; 

// 函数声明
static void hide_error_timer_cb(lv_timer_t *timer);
static void button1_event_handler(lv_event_t *e);
static void hide_keyboard(void);
static void ta_event_cb(lv_event_t *e);
static void check_input_complete();
static int compare_dates(const void *a, const void *b);
static void calculate_days_range(void);
static void update_calendar_highlight();
static void sig_handler(int signo);
static void on_screen6_displayed(lv_event_t * e); 
static void on_screen_loaded(lv_event_t *e);   
void setup_ui(void);

// 最大支持选中的日期数量
#define MAX_SELECTED_DATES 31

static void reset_previous_screen(lv_timer_t * t) {
    previous_screen = NULL;
    printf("已重置previous_screen\n");
    lv_timer_del(t);
}

#if 1
// 调试函数：打印当前屏幕树状结构
static void print_screen_hierarchy(lv_obj_t * parent, int level) {
    for(int i = 0; i < level; i++) printf("  ");
    printf("%p [%s] %s%s\n", 
           parent,
           "Object", // 替换原lv_obj_get_class(parent)->name
           lv_obj_has_flag(parent, LV_OBJ_FLAG_HIDDEN) ? "HIDDEN " : "",
           lv_obj_has_state(parent, LV_STATE_USER_1) ? "DISABLED " : "");
           
    lv_obj_t * child = lv_obj_get_child(parent, 0);
    while(child) {
        print_screen_hierarchy(child, level + 1);
        child = lv_obj_get_child(parent, lv_obj_get_index(child) + 1);
    }
}

// 检查屏幕切换状态
static void check_screen_state() {
    printf("\n当前屏幕状态:\n");
    print_screen_hierarchy(lv_layer_top(), 0);
    printf("----------------\n");
    printf("Previous screen: %p\n", previous_screen);
    printf("Current screen: %p\n", lv_scr_act());
    printf("Keyboard: %p\n", kb);
}
#endif

// 替换原来的lambda表达式为普通函数
static void delayed_screen_reset(lv_timer_t * t) {
    previous_screen = NULL;
    lv_timer_del(t);
}

static void show_screen6_cb(lv_timer_t * t) {
    _ui_flag_modify(ui_Screen6, LV_OBJ_FLAG_HIDDEN, _UI_MODIFY_FLAG_REMOVE);
    lv_timer_del(t);
}

// 日期比较函数，用于qsort排序
static int compare_dates(const void *a, const void *b) {
    const lv_calendar_date_t *date1 = (const lv_calendar_date_t *)a;
    const lv_calendar_date_t *date2 = (const lv_calendar_date_t *)b;
    
    // 1. 比较年份
    if(date1->year < date2->year) return -1;
    if(date1->year > date2->year) return 1;
    
    // 2. 年份相同则比较月份
    if(date1->month < date2->month) return -1;
    if(date1->month > date2->month) return 1;
    
    // 3. 年月相同则比较日
    if(date1->day < date2->day) return -1;
    if(date1->day > date2->day) return 1;
    
    // 完全相同
    return 0;
}

// 存储选中日期的数组和计数
static lv_calendar_date_t selected_dates[MAX_SELECTED_DATES];
static uint16_t selected_count = 0;

// 全局错误处理
static void signal_handler(int sig) {
    printf("捕获到信号 %d，重置日历状态\n", sig);
    selected_count = 0;
    memset(selected_dates, 0, sizeof(selected_dates));
    lv_textarea_set_text(ui_TextArea13, "0");
    lv_textarea_set_text(ui_TextArea14, "0");
    lv_obj_invalidate(ui_Calendar1);
    _exit(1);
}

// 添加或移除选中日期
static void toggle_date_selection(const lv_calendar_date_t *date) {
    // 安全检查
    if(date == NULL || date->year == 0) {
        printf("无效日期参数\n");
        return;
    }

    printf("操作前 - 选中数: %d\n", selected_count);
    
    // 查找日期是否已存在
    int found_index = -1;
    for(int i = 0; i < selected_count; i++) {
        if(selected_dates[i].year == date->year &&
           selected_dates[i].month == date->month &&
           selected_dates[i].day == date->day) {
            found_index = i;
            break;
        }
    }

    if(found_index >= 0) {
        // 移除日期
        if(selected_count > 1 && found_index < selected_count - 1) {
            memmove(&selected_dates[found_index], 
                   &selected_dates[found_index+1],
                   (selected_count - found_index - 1) * sizeof(lv_calendar_date_t));
        }
        selected_count--;
        
        printf("移除日期: %d-%02d-%02d (剩余: %d)\n",
              date->year, date->month, date->day, selected_count);
    } else {
        // 添加新日期
        if(selected_count < MAX_SELECTED_DATES) {
            selected_dates[selected_count] = *date;
            selected_count++;
            printf("添加日期: %d-%02d-%02d (总数: %d)\n",
                  date->year, date->month, date->day, selected_count);
        }
    }

    // 强制状态重置（关键修复）
    if(selected_count == 0) {
        memset(selected_dates, 0, sizeof(selected_dates));
    }

    // 更新UI（严格顺序）
    update_calendar_highlight();
    calculate_days_range();
    lv_obj_invalidate(ui_Calendar1);
    lv_refr_now(NULL);  // 强制立即刷新
    
    printf("操作后 - 选中数: %d\n", selected_count);
    printf("----------------------------\n");
}

static void handle_sigsegv(int sig) {
    printf("\n!!! 崩溃信号捕获 !!!\n");
    check_screen_state();
    
    // 重置关键状态
    selected_count = 0;
    memset(selected_dates, 0, sizeof(selected_dates));
    previous_screen = NULL;
    
    // 强制显示主屏幕
    lv_obj_t * main_screen = ui_Screen1; // 根据实际情况调整
    _ui_screen_change(&main_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
    
    exit(1);
}

// 更新日历高亮显示
static void update_calendar_highlight() {
    if(selected_count > 0) {
        lv_calendar_set_highlighted_dates(ui_Calendar1, selected_dates, selected_count);
    } else {
        // 完全清空高亮（关键修改）
        lv_calendar_date_t empty_dates[] = {0}; // 确保这不是const
        lv_calendar_set_highlighted_dates(ui_Calendar1, empty_dates, 0);
    }
    lv_obj_invalidate(ui_Calendar1);
}
// 计算选中日期的天数范围
static void calculate_days_range() {
    if(selected_count == 0) {
        lv_textarea_set_text(ui_TextArea13, "0");
        lv_textarea_set_text(ui_TextArea14, "0");
        return;
    }

    // 排序日期确保正确计算
    qsort(selected_dates, selected_count, sizeof(lv_calendar_date_t), compare_dates);

    // 安全转换日期结构
    struct tm tm_start = {
        .tm_year = selected_dates[0].year - 1900,
        .tm_mon = selected_dates[0].month - 1,
        .tm_mday = selected_dates[0].day,
        .tm_isdst = -1 // 自动处理夏令时
    };
    
    struct tm tm_end = {
        .tm_year = selected_dates[selected_count-1].year - 1900,
        .tm_mon = selected_dates[selected_count-1].month - 1,
        .tm_mday = selected_dates[selected_count-1].day,
        .tm_isdst = -1
    };

    time_t start = mktime(&tm_start);
    time_t end = mktime(&tm_end);
    
    if(start == -1 || end == -1) {
        lv_textarea_set_text(ui_TextArea13, "0");
        lv_textarea_set_text(ui_TextArea14, "0");
        return;
    }

    int days = (int)(difftime(end, start) / 86400) + 1;
    char buf[16];
    snprintf(buf, sizeof(buf), "%d", days);
    lv_textarea_set_text(ui_TextArea13, buf);
    snprintf(buf, sizeof(buf), "%d", days * 24);
    lv_textarea_set_text(ui_TextArea14, buf);
}

// 日历点击事件处理
static void calendar_event_handler(lv_event_t *e) {
    lv_calendar_date_t clicked_date;
    if(!lv_calendar_get_pressed_date(ui_Calendar1, &clicked_date)) {
        printf("点击无效或未获取到日期\n");
        return;
    }

    printf("点击日期: %d-%02d-%02d\n", clicked_date.year, clicked_date.month, clicked_date.day);
    printf("当前选中数: %d\n", selected_count);
    
    toggle_date_selection(&clicked_date);
    
    printf("操作后选中数: %d\n", selected_count);
    printf("----------------------------\n");
}

// 设置日历显示当前日期
static void init_calendar_with_current_date() {
    time_t now = time(NULL);
    struct tm *tm_info = localtime(&now);
    
    lv_calendar_date_t today;
    today.year = tm_info->tm_year + 1900;
    today.month = tm_info->tm_mon + 1;
    today.day = tm_info->tm_mday;
    
    // 设置日历显示当前月份
    lv_calendar_set_showed_date(ui_Calendar1, today.year, today.month);
}

// 初始化日历
void init_calendar() {
    selected_count = 0; // 重置选中计数
    
    // 设置当前日期
    init_calendar_with_current_date();
    
    // 绑定事件
    lv_obj_add_event_cb(ui_Calendar1, calendar_event_handler, LV_EVENT_VALUE_CHANGED, NULL);
}

// 隐藏键盘
static void hide_keyboard(void) {
    if (kb) {
        lv_keyboard_set_textarea(kb, NULL);
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
    }
}

// 更新时间显示
static void update_time_display(lv_timer_t *timer) {
    time_t now = time(NULL);
    struct tm *tm_info = localtime(&now);
    
    // 1. 更新日期（YYYY-MM-DD）
    char date_str[20];
    strftime(date_str, sizeof(date_str), "%Y-%m-%d", tm_info);
    lv_label_set_text(ui_Label3, date_str);
	lv_label_set_text(ui_Label51, date_str);
	lv_label_set_text(ui_Label54, date_str);
	lv_label_set_text(ui_Label57, date_str);
	lv_label_set_text(ui_Label63, date_str);
	lv_label_set_text(ui_Label66, date_str);
	lv_label_set_text(ui_Label69, date_str);
	lv_label_set_text(ui_Label72, date_str);
	lv_label_set_text(ui_Label75, date_str);
    
    // 2. 更新星期（Mon, Tue...）
    char weekday_str[10];
    strftime(weekday_str, sizeof(weekday_str), "%a", tm_info);
    lv_label_set_text(ui_Label4, weekday_str);
	lv_label_set_text(ui_Label52, weekday_str);
	lv_label_set_text(ui_Label55, weekday_str);
	lv_label_set_text(ui_Label58, weekday_str);
	lv_label_set_text(ui_Label64, weekday_str);
	lv_label_set_text(ui_Label67, weekday_str);
	lv_label_set_text(ui_Label70, weekday_str);
	lv_label_set_text(ui_Label73, weekday_str);
	lv_label_set_text(ui_Label76, weekday_str);
    
    // 3. 更新时间（HH:MM:SS）
    char time_str[10];
    strftime(time_str, sizeof(time_str), "%H:%M:%S", tm_info);
    lv_label_set_text(ui_Label5, time_str);
	lv_label_set_text(ui_Label53, time_str);
	lv_label_set_text(ui_Label56, time_str);
	lv_label_set_text(ui_Label59, time_str);
	lv_label_set_text(ui_Label65, time_str);
	lv_label_set_text(ui_Label68, time_str);
	lv_label_set_text(ui_Label71, time_str);
	lv_label_set_text(ui_Label74, time_str);
	lv_label_set_text(ui_Label77, time_str);
}

void init_auto_time_update() {
    // 如果定时器不存在，就创建它（每秒更新一次）
    if (!time_update_timer) {
        time_update_timer = lv_timer_create(update_time_display, 1000, NULL);
        lv_timer_set_repeat_count(time_update_timer, -1);  // 无限循环
    }
    
    // 立即更新一次，避免初始延迟
    update_time_display(NULL);
}

static void ta_event_cb(lv_event_t *e) {
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t *ta = lv_event_get_target(e);
    lv_obj_t *parent_screen = lv_obj_get_screen(ta);

    // 只处理目标文本框
    if (ta != ui_TextArea3 && ta != ui_TextArea4 && 
        ta != ui_TextArea5 && ta != ui_TextArea6 && 
        ta != ui_TextArea7 && ta != ui_TextArea8 ) {
        return;
    }

    // 如果键盘未创建或父屏幕已切换，则重新创建键盘
    if (kb == NULL || parent_screen != current_kb_parent) {
        if (kb) lv_obj_del(kb);
        kb = lv_keyboard_create(parent_screen);
        lv_obj_set_size(kb, LV_PCT(100), LV_PCT(40));
        lv_obj_align(kb, LV_ALIGN_BOTTOM_MID, 0, 0);
        lv_obj_add_flag(kb, LV_OBJ_FLAG_HIDDEN);
        current_kb_parent = parent_screen;
    }

    if (code == LV_EVENT_CLICKED || code == LV_EVENT_FOCUSED) {
        lv_keyboard_set_textarea(kb, ta);
        lv_obj_clear_flag(kb, LV_OBJ_FLAG_HIDDEN);
        lv_obj_move_foreground(kb);
    } 
    else if (code == LV_EVENT_DEFOCUSED || code == LV_EVENT_READY) {
        hide_keyboard();
    }
}

// 修改后的检查输入函数
static void check_input_complete() {
    const char *user = lv_textarea_get_text(ui_TextArea3);
    const char *pwd = lv_textarea_get_text(ui_TextArea4);
    
    if (user && pwd && strlen(user) > 0 && strlen(pwd) > 0) {
        // 有输入时检查账号密码
        if (strcmp(user, "123456GZ") == 0 && strcmp(pwd, "11112222") == 0) {
            lv_obj_clear_state(ui_Button3, LV_STATE_DISABLED);
        } else {
            lv_obj_add_state(ui_Button3, LV_STATE_DISABLED);
        }
    } else {
        // 无输入时禁用按钮
        lv_obj_add_state(ui_Button3, LV_STATE_DISABLED);
    }
}

// 登录按钮事件处理
static void button1_event_handler(lv_event_t *e) {
    hide_keyboard();
    const char *username = lv_textarea_get_text(ui_TextArea3);
    const char *password = lv_textarea_get_text(ui_TextArea4);

    if (!username || !password || strlen(username) == 0 || strlen(password) == 0) {
        if (!error_label) {
            error_label = lv_label_create(lv_scr_act());
            lv_obj_set_style_text_color(error_label, lv_color_hex(0xFF0000), LV_PART_MAIN);
            lv_obj_align(error_label, LV_ALIGN_TOP_MID, 0, 20);
        }
        lv_label_set_text(error_label, "Please input username and password");
        lv_obj_clear_flag(error_label, LV_OBJ_FLAG_HIDDEN);
        lv_timer_create(hide_error_timer_cb, 3000, NULL);
        return;
    }

    if (strcmp(username, "123456GZ") == 0 && strcmp(password, "11112222") == 0) {
        lv_obj_t *target_screen = ui_Screen3;
        _ui_screen_change(&target_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
    } else {
        if (!error_label) {
            error_label = lv_label_create(lv_scr_act());
            lv_obj_set_style_text_color(error_label, lv_color_hex(0xFF0000), LV_PART_MAIN);
            lv_obj_align(error_label, LV_ALIGN_TOP_MID, 0, 20);
        }
        lv_label_set_text(error_label, "Account or password error");
        lv_obj_clear_flag(error_label, LV_OBJ_FLAG_HIDDEN);
        lv_timer_create(hide_error_timer_cb, 3000, NULL);
    }
}

// Screen4 确认按钮事件
static void confirm_button_handler(lv_event_t *e) {
    hide_keyboard();
}

static void hide_error_timer_cb(lv_timer_t *timer) {
    if (error_label) {
        lv_obj_add_flag(error_label, LV_OBJ_FLAG_HIDDEN);
    }
    lv_timer_del(timer);
}

void get_user(lv_event_t *e) {
	setup_ui();
}

void get_password(lv_event_t *e) {
    setup_ui();
}

void setup_ui() {
    static bool is_initialized = false;
    if (is_initialized) return;
     // 初始化前重置所有关键状态
    previous_screen = NULL;
    selected_count = 0;
    memset(selected_dates, 0, sizeof(selected_dates));

    lv_obj_add_event_cb(ui_Screen6, on_screen_loaded, LV_EVENT_SCREEN_LOADED, NULL);
    lv_obj_add_event_cb(ui_Screen7, on_screen_loaded, LV_EVENT_SCREEN_LOADED, NULL);
    
    
    // 注册信号处理器
    signal(SIGSEGV, handle_sigsegv);
    signal(SIGABRT, handle_sigsegv);

    is_initialized = true;

     // 1. 先注册信号处理器（放在其他初始化之前）
    signal(SIGSEGV, handle_sigsegv);

    printf("UI初始化检查:\n");
    printf("ui_Screen6: %p\n", ui_Screen6);
    printf("ui_Screen8: %p\n", ui_Screen8);
    printf("当前屏幕: %p\n", lv_scr_act());

    // 初始化选中日期数组
    selected_count = 0;
    memset(selected_dates, 0, sizeof(selected_dates));
    

    init_calendar();
     // 初始显示0
    lv_textarea_set_text(ui_TextArea13, "0");
    lv_textarea_set_text(ui_TextArea14, "0");
    
    // 绑定Screen2的事件
    lv_obj_add_event_cb(ui_TextArea3, ta_event_cb, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_TextArea4, ta_event_cb, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_Button3, button1_event_handler, LV_EVENT_CLICKED, NULL);

    // 绑定Screen4的事件
    lv_obj_add_event_cb(ui_TextArea5, ta_event_cb, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_TextArea6, ta_event_cb, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_TextArea7, ta_event_cb, LV_EVENT_ALL, NULL);
    lv_obj_add_event_cb(ui_TextArea8, ta_event_cb, LV_EVENT_ALL, NULL);
    
    // 绑定Screen5的事件
    lv_obj_add_event_cb(ui_Button4, confirm_button_handler, LV_EVENT_CLICKED, NULL);
    lv_obj_add_event_cb(ui_Button4, get_Name1, LV_EVENT_CLICKED, NULL);
	
    // 新增：设置密码框为加密显示（显示为*）
    lv_textarea_set_password_mode(ui_TextArea4, true);       // 启用密码模式
    lv_textarea_set_password_bullet(ui_TextArea4, "*");     // 设置显示的字符为*
    lv_textarea_set_one_line(ui_TextArea4, true); // 强制单行输入

    // 初始化日历显示当前日期
    init_calendar_with_current_date();

    if(ui_Screen6 && ui_Label78) {
        lv_obj_add_event_cb(ui_Screen6, get_times1, LV_EVENT_SCREEN_LOADED, NULL);
    }
    // 添加信号处理
    signal(SIGABRT, signal_handler);
}

// 信号处理函数
static void sig_handler(int signo) {
    printf("Caught signal %d, resetting calendar...\n", signo);
    selected_count = 0;
    memset(selected_dates, 0, sizeof(selected_dates));
    lv_textarea_set_text(ui_TextArea13, "0");
    lv_textarea_set_text(ui_TextArea14, "0");
    lv_obj_invalidate(ui_Calendar1);
}

// 空函数（保持兼容性）
void init_datetime_display(void) {}

void update_display_counter(lv_obj_t* label) {
    static int count = 0;  // 改用static避免全局变量
    count++;
    char buf[16];
    snprintf(buf, sizeof(buf), "%d", count);
    lv_label_set_text(label, buf);
}

void set_display_counter_label(lv_obj_t* label) {
    // 空实现（或初始化计数）
}

// 专用计数函数
// 在文件后面添加函数实现（放在其他函数后面）
static void on_screen6_displayed(lv_event_t * e) {
    // 1. 验证事件来源
    if (lv_event_get_code(e) != LV_EVENT_SCREEN_LOADED) return;
    if (lv_event_get_current_target(e) != ui_Screen6) return;

    // 2. 专属计数器
    static int screen6_display_count = 0;
    screen6_display_count++;
    
    // 3. 更新UI
    char buf[16];
    snprintf(buf, sizeof(buf), "%d", screen6_display_count);
    lv_label_set_text(ui_Label78, buf);

    printf("[安全计数] ui_Screen6显示次数: %d\n", screen6_display_count);
}

// 修改后的计数函数
void get_times1(lv_event_t * e) {
    /* 只处理屏幕加载完成事件 */
    if(lv_event_get_code(e) != LV_EVENT_SCREEN_LOADED) return;
    
    static int screen6_count = 0;
    screen6_count++;  // 确保每次只加1
    
    char buf[16];
    snprintf(buf, sizeof(buf), "%d", screen6_count);
    lv_label_set_text(ui_Label78, buf);
    printf("ui_Screen6显示次数: %d\n", screen6_count);
}

void get_times2(lv_event_t * e) {
    /* 只处理屏幕加载完成事件 */
    if(lv_event_get_code(e) != LV_EVENT_SCREEN_LOADED) return;
    
    static int screen7_count = 0;
    screen7_count++;  // 确保每次只加1
    
    char buf[16];
    snprintf(buf, sizeof(buf), "%d", screen7_count);
    lv_label_set_text(ui_Label79, buf);
    printf("ui_Screen7显示次数: %d\n", screen7_count);
}

void get_Times1(lv_event_t * e) {
    /* 只处理屏幕加载完成事件 */
    if(lv_event_get_code(e) != LV_EVENT_SCREEN_LOADED) return;
    
    static int screen9_count = 0;
    screen9_count++;  // 确保每次只加1
    
    char buf[16];
    snprintf(buf, sizeof(buf), "%d", screen9_count);
    lv_label_set_text(ui_Label41, buf);
    printf("ui_Screen9显示次数: %d\n", screen9_count);
}

void get_Times2(lv_event_t * e) {
    /* 只处理屏幕加载完成事件 */
    if(lv_event_get_code(e) != LV_EVENT_SCREEN_LOADED) return;
    
    static int screen10_count = 0;
    screen10_count++;  // 确保每次只加1
    
    char buf[16];
    snprintf(buf, sizeof(buf), "%d", screen10_count);
    lv_label_set_text(ui_Label48, buf);
    printf("ui_Screen10显示次数: %d\n", screen10_count);
}

void get_Name1(lv_event_t * e) {
    // 1. 安全检查
    if (!ui_TextArea7 || !ui_TextArea8 || !ui_TextArea15 || !ui_TextArea16) {
        printf("Error: UI elements not initialized!\n");
        printf("ui_TextArea7: %p\n", ui_TextArea7);
        printf("ui_TextArea8: %p\n", ui_TextArea8);
        printf("ui_TextArea15: %p\n", ui_TextArea15);
        printf("ui_TextArea16: %p\n", ui_TextArea16);
        return;
    }

    // 2. 获取性别和姓名
    const char* gender = lv_textarea_get_text(ui_TextArea7);
    const char* name = lv_textarea_get_text(ui_TextArea8);
    
    printf("获取到的性别: %s\n", gender ? gender : "NULL");
    printf("获取到的姓名: %s\n", name ? name : "NULL");

    // 3. 根据性别设置不同的文本区域
    if (gender && name) {
        if (strcmp(gender, "boy") == 0) {
            lv_textarea_set_text(ui_TextArea15, name);  // 男性数据传到屏幕9
            lv_textarea_set_text(ui_TextArea16, "");    // 清空女性文本框
        } 
        else if (strcmp(gender, "girl") == 0) {
            lv_textarea_set_text(ui_TextArea16, name);  // 女性数据传到屏幕10
            lv_textarea_set_text(ui_TextArea15, "");    // 清空男性文本框
        } 
        else {
            // 默认情况或无效性别
            lv_textarea_set_text(ui_TextArea15, "");  // 默认值
            lv_textarea_set_text(ui_TextArea16, ""); // 默认值
        }
    } else {
        // 无输入时的默认值
        lv_textarea_set_text(ui_TextArea15, "");
        lv_textarea_set_text(ui_TextArea16, "");
    }
}


// 屏幕加载事件处理函数
// 屏幕加载事件处理函数
static void on_screen_loaded(lv_event_t *e) {
    if(lv_event_get_code(e) != LV_EVENT_SCREEN_LOADED) return;
    
    lv_obj_t *screen = lv_event_get_target(e);
    printf("Screen loaded: %p\n", screen);
    
    if(screen == ui_Screen6) {  // 使用正确的屏幕变量
        printf("Screen6 loaded\n");
        // 这里可以添加Screen6特定的初始化代码
    }
}



void get_currentdayte(lv_event_t * e)
{
	init_calendar_with_current_date();
}

static void hide_timer_cb(lv_timer_t * timer)
{
    lv_obj_t * screen = (lv_obj_t *)timer->user_data;
    _ui_flag_modify(screen, LV_OBJ_FLAG_HIDDEN, _UI_MODIFY_FLAG_REMOVE);
    lv_timer_del(timer);
}

static void print_screen_info(const char* name, const lv_obj_t* obj) {
    if(obj == NULL) {
        printf("[%s]: NULL\n", name);
        return;
    }
    
    lv_area_t coords;
    lv_obj_get_coords(obj, &coords);
    
    printf("[%s]\n", name);
    printf("  地址: %p\n", obj);
    printf("  类: %p\n", lv_obj_get_class(obj));
    printf("  父对象: %p\n", lv_obj_get_parent(obj));
    printf("  所属屏幕: %p\n", lv_obj_get_screen(obj));
    printf("  坐标: (%d,%d)-(%d,%d)\n", 
           coords.x1, coords.y1, coords.x2, coords.y2);
    printf("  状态: %s%s\n",
           lv_obj_has_flag(obj, LV_OBJ_FLAG_HIDDEN) ? "HIDDEN " : "",
           lv_obj_has_state(obj, LV_STATE_USER_1) ? "DISABLED " : "");
}

static bool is_screen_valid(const lv_obj_t * obj) {
    // 基础检查
    if(obj == NULL || lv_obj_get_class(obj) == NULL) return false;
    
    // 屏幕对象的特殊检查
    if(lv_obj_get_parent(obj) != NULL) return false; // 屏幕应该没有父对象
    if(lv_obj_get_screen(obj) != obj) return false;  // 屏幕的screen应该是自己
    
    // 检查基本属性
    lv_area_t coords;
    lv_obj_get_coords(obj, &coords);
    return (coords.x2 > coords.x1) && (coords.y2 > coords.y1);
}

void get_ask1(lv_event_t * e)
{
    lv_event_code_t event_code = lv_event_get_code(e);
    
    if(event_code == LV_EVENT_CLICKED) {
        printf("\n----- 准备切换到Screen8 -----\n");
        
        // 1. 记录来源屏幕（仅当不同时才更新）
        lv_obj_t * current_screen = lv_scr_act();
        if(previous_screen != current_screen) {
            previous_screen = current_screen;
            printf("记录来源屏幕: %p\n", previous_screen);
        }

        // 2. 切换到Screen8（不再隐藏Screen6）
        if(ui_Screen8) {
            lv_obj_t * target = ui_Screen8;
            _ui_screen_change(&target, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
            lv_refr_now(NULL);
            printf("已切换到Screen8: %p\n", lv_scr_act());
        }
    }

 // 在UI构建器中确保为ui_Label78设置了事件回调
 lv_obj_add_event_cb(ui_Label78, get_times1, LV_EVENT_ALL, NULL);

}
     
void get_ask2(lv_event_t * e)
{
	 lv_event_code_t event_code = lv_event_get_code(e);
    
    if(event_code == LV_EVENT_CLICKED) {
        printf("\n----- 准备切换到Screen8 -----\n");
        
        // 1. 记录来源屏幕（仅当不同时才更新）
        lv_obj_t * current_screen = lv_scr_act();
        if(previous_screen != current_screen) {
            previous_screen = current_screen;
            printf("记录来源屏幕: %p\n", previous_screen);
        }

        // 2. 切换到Screen8（不再隐藏Screen6）
        if(ui_Screen8) {
            lv_obj_t * target = ui_Screen8;
            _ui_screen_change(&target, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
            lv_refr_now(NULL);
            printf("已切换到Screen8: %p\n", lv_scr_act());
        }
    }
}

void ask_arrive(lv_event_t * e)
{
    lv_event_code_t event_code = lv_event_get_code(e);
    
    if(event_code == LV_EVENT_CLICKED) {
        printf("\n----- 返回按钮点击 -----\n");
        print_screen_info("当前屏幕", lv_scr_act());
        print_screen_info("previous_screen", previous_screen);

        // 1. 强制完成所有待处理操作
        lv_refr_now(NULL);

        // 2. 确保previous_screen有效且不是当前屏幕
        if(previous_screen && 
           previous_screen != lv_scr_act() &&
           lv_obj_get_class(previous_screen))
        {
            // 3. 确保Screen6完全可见（关键修复）
            if(previous_screen == ui_Screen6) {
                lv_obj_clear_state(ui_Screen6, LV_STATE_USER_1); // 清除可能存在的禁用状态
                _ui_flag_modify(ui_Screen6, LV_OBJ_FLAG_HIDDEN, _UI_MODIFY_FLAG_REMOVE);
                printf("强制显示ui_Screen6\n");
            }

            // 4. 执行无动画切换（避免可能的动画冲突）
            lv_obj_t * target = previous_screen;
            _ui_screen_change(&target, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
            
            // 5. 强制刷新并验证
            lv_refr_now(NULL);
            printf("切换后活动屏幕: %p\n", lv_scr_act());
            
            // 6. 打印调试信息
            printf("----- 切换验证 -----\n");
            printf("预期屏幕: %p\n", previous_screen);
            printf("实际屏幕: %p\n", lv_scr_act());
            printf("是否匹配: %s\n", 
                  (previous_screen == lv_scr_act()) ? "是" : "否");
            
            // 7. 重置previous_screen
            previous_screen = NULL;
        } else {
            printf("错误：无效的previous_screen！回退到主屏幕\n");
            lv_obj_t * main_screen = ui_Screen1;
            _ui_screen_change(&main_screen, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
        }
    }
}

void get_ask3(lv_event_t * e)
{
	lv_event_code_t event_code = lv_event_get_code(e);
    
    if(event_code == LV_EVENT_CLICKED) {
        printf("\n----- 准备切换到Screen8 -----\n");
        
        // 1. 记录来源屏幕（仅当不同时才更新）
        lv_obj_t * current_screen = lv_scr_act();
        if(previous_screen != current_screen) {
            previous_screen = current_screen;
            printf("记录来源屏幕: %p\n", previous_screen);
        }

        // 2. 切换到Screen8（不再隐藏Screen6）
        if(ui_Screen8) {
            lv_obj_t * target = ui_Screen8;
            _ui_screen_change(&target, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
            lv_refr_now(NULL);
            printf("已切换到Screen8: %p\n", lv_scr_act());
        }
    }
}

void get_ask4(lv_event_t * e)
{
	lv_event_code_t event_code = lv_event_get_code(e);
    
    if(event_code == LV_EVENT_CLICKED) {
        printf("\n----- 准备切换到Screen8 -----\n");
        
        // 1. 记录来源屏幕（仅当不同时才更新）
        lv_obj_t * current_screen = lv_scr_act();
        if(previous_screen != current_screen) {
            previous_screen = current_screen;
            printf("记录来源屏幕: %p\n", previous_screen);
        }

        // 2. 切换到Screen8（不再隐藏Screen6）
        if(ui_Screen8) {
            lv_obj_t * target = ui_Screen8;
            _ui_screen_change(&target, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
            lv_refr_now(NULL);
            printf("已切换到Screen8: %p\n", lv_scr_act());
        }
    }
}

// 修改按钮回调函数，确保只触发一次屏幕切换
void ui_Button1_callback(lv_event_t * e) {
    if(lv_event_get_code(e) == LV_EVENT_CLICKED) {
        // 绑定屏幕6的计数事件（如果尚未绑定）
        static bool screen6_initialized = false;
        if(!screen6_initialized && ui_Screen6 && ui_Label78) {
            lv_obj_add_event_cb(ui_Screen6, get_times1, LV_EVENT_SCREEN_LOADED, NULL);
            screen6_initialized = true;
            printf("绑定ui_Screen6计数事件\n");
        }
        _ui_screen_change(&ui_Screen6, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
    }
}

void ui_Button10_callback(lv_event_t * e) {
    if(lv_event_get_code(e) == LV_EVENT_CLICKED) {
        // 绑定屏幕7的计数事件（如果尚未绑定）
        static bool screen7_initialized = false;
        if(!screen7_initialized && ui_Screen7 && ui_Label79) {
            lv_obj_add_event_cb(ui_Screen7, get_times2, LV_EVENT_SCREEN_LOADED, NULL);
            screen7_initialized = true;
            printf("绑定ui_Screen7计数事件\n");
        }
        _ui_screen_change(&ui_Screen7, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
    }
}

void ui_Button11_callback(lv_event_t * e) {
    if(lv_event_get_code(e) == LV_EVENT_CLICKED) {
        // 先更新数据
        get_Name1(e);
        
        // 然后切换屏幕
        static bool screen9_initialized = false;
        if(!screen9_initialized && ui_Screen9 && ui_Label41) {
            lv_obj_add_event_cb(ui_Screen9, get_Times1, LV_EVENT_SCREEN_LOADED, NULL);
            screen9_initialized = true;
            printf("绑定ui_Screen9计数事件\n");
        }
        _ui_screen_change(&ui_Screen9, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
    }
}

void ui_Button13_callback(lv_event_t * e) {
    if(lv_event_get_code(e) == LV_EVENT_CLICKED) {
        // 先更新数据
        get_Name1(e);
        
        // 然后切换屏幕
        static bool screen10_initialized = false;
        if(!screen10_initialized && ui_Screen10 && ui_Label48) {
            lv_obj_add_event_cb(ui_Screen10, get_Times2, LV_EVENT_SCREEN_LOADED, NULL);
            screen10_initialized = true;
            printf("绑定ui_Screen10计数事件\n");
        }
        _ui_screen_change(&ui_Screen10, LV_SCR_LOAD_ANIM_NONE, 0, 0, NULL);
    }
}
